package com.backend.controller;


import com.backend.common.*;
import com.backend.exception.BusinessException;
import com.backend.exception.ThrowUtils;
import com.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencentcloudapi.kms.v20190118.models.EnableKeyRotationRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.backend.entity.User;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


/**
 * 用户接口
 *
 * 具备如下功能：
 *
 * 名称               URL              参数                  返回的结果
 * 登录               /login           User,request          token
 * 注册               /register        User                  ()
 * 退出               /logout          request               ()
 * Session获取        /session         request               user
 * 重置密码            /resetPass       user                  ()
 * 分页               /page            params,User           pgae
 * 用户列表            /list            params,User           List<User>
 * 查询               /query           User                  UserView
 * 详情               /detail/{id}     id                    User
 * 添加               /add             User                  ()
 * 修改               /update          User                  ()
 * 删除               /delete          long[] ids            ()
 *
 *
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public BaseResponse<?> userLogin(@RequestBody User user, HttpServletRequest request) {

        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userName = user.getUserName();
        String userPassword = user.getUserPassword();
        if (StringUtils.isAnyBlank(userName, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        User resultUser = userService.userLogin(userName, userPassword, request);
        if (resultUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        HashMap map = new HashMap();
        map.put("user", resultUser);
        map.put("menu", "menus");
        return ResultUtils.ok(map);
    }


    /**
     * 注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userName = user.getUserName();
        String userPassword = user.getUserPassword();
        if (StringUtils.isAnyBlank(userName, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        long result = userService.userRegister(userName, userPassword);
        return ResultUtils.ok(result);
    }

    /**
     * 退出
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = userService.userLogout(request);
        return ResultUtils.ok(result);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/{id}")
    public BaseResponse<User> getUserById(@PathVariable("id") String id, HttpServletRequest request) {
        User user = userService.getById(Integer.parseInt(id));
        return ResultUtils.ok(user);
    }

    @GetMapping("/resetPassword")
    public BaseResponse<?> resetPassword(User user) {
        Boolean isResetSuccessful = userService.resetPassword(user);
        return ResultUtils.ok(isResetSuccessful);
    }


    /**
     * 添加
     */
    @PostMapping("/add")
    public BaseResponse<?> addUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(User::getUserName, user.getUserName());
        long count = userService.count(lambdaQueryWrapper);
        if (count > 0 ) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户已存在");
        }
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.ok(user.getId());
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody Long[] ids, HttpServletRequest request) {
        userService.removeByIds(Arrays.asList(ids));
        return ResultUtils.ok(null);
    }

    /**
     * 更新
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null || user.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.ok(null);
    }

    @GetMapping("/lists")
    public BaseResponse<List<User>> lists() {
        return ResultUtils.ok(userService.list());
    }

    @PostMapping("/page")
    public BaseResponse<PageResponse> page(@RequestBody PageRequest pageRequest) {
        PageResponse result = userService.page(pageRequest);
        return ResultUtils.ok(result);
    }

    @PostMapping("/detail/{id}")
    public BaseResponse<User> detail(@PathVariable("id")String id) {
        User user = userService.getById(id);
        System.out.println(id.getClass().toString());
        return ResultUtils.ok(user);
    }
}





